﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Script specifically for the Boss enemy 
/// similar to AiShoot except that instead shooting bullets it will fire out small enemies to home in on the player.  
/// The Ai component of these is initially disabled so they spread out before attacking which works a lot better
/// </summary>
public class Boss : MonoBehaviour {


    public GameObject Bullet, Spawn;
    public float RoF;
    
    public float NextFire = 1.0f;

    Ai Bot;
    int LM;

    void Start() {
        Bot = GetComponent<Ai>();
        rigidbody2D.isKinematic = true; ;               
    }

    void Update() {
        if(Bot.enabled == false) {           
            Vector2 vec = Spawn.transform.position - transform.position;

            Debug.DrawLine(transform.position + (Vector3)vec, transform.position, Color.red);
            float dis = vec.magnitude, delta = Time.deltaTime * Bot.speed;

            if(delta > dis) {
                Bot.enabled = true;
                rigidbody2D.isKinematic = false;               
            } else {
                vec.Normalize();
                transform.position += (Vector3)(vec * (delta));
                return;
            }
        }

        if(Bot.Target == null) return;

        if((NextFire -= Time.deltaTime) > 0) return;

        int amnt = Random.Range(3, 6);
        NextFire = (float)amnt  /RoF;   //Random.Range(2.0f, 3.0f) * RoF;
        Bot.Slow = 0.99f;

        for(int i = amnt; i-- > 0; ) {

            Vector2 off = Random.insideUnitCircle;
            var go = Instantiate(Bullet, transform.position + (Vector3)off, Quaternion.identity) as GameObject;
            var bullet =  go.GetComponent<Ai>();
            bullet.FFD.set(Mathf.Rad2Deg * Mathf.Atan2(off.y, off.x));
            go.rigidbody2D.velocity = off * 8.0f;
            bullet.FFD.StartCoroutine(spawn(Random.Range(1.0f, 3.0f), bullet));
        }

      
    }

    void OnDisable() {
        FindObjectOfType<WaveMan>().nextScene();
    }

    IEnumerator spawn(float delay, Ai bullet) {
        for(; ; ) {
            if((delay -= Time.deltaTime) < 0) break;
            var vel = bullet.rigidbody2D.velocity;
            bullet.FFD.GetComponent<FrameFromDirection>().set(Mathf.Rad2Deg * Mathf.Atan2(vel.y, vel.x));
            yield return new YieldInstruction();
        }
        bullet.enabled = true;
    }
}
